package com.ray.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.VisitorMapper;
import com.ray.pojo.AttendDevicePojo;
import com.ray.pojo.AttendSourceRecordPojo;
import com.ray.util.ConfigUtil;
import com.ray.util.DingTalkUtil;
import com.ray.util.callback.CallBackBody;
import com.ray.util.callback.CallBackTask;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;

@Service
public class VisitorService {
	
	@Autowired
	VisitorMapper visitorMapper;
	@Autowired
	BasicDataService basicDataService;
	@Autowired
	DingTalkService dingTalkService;
	@Autowired
	WeiXinService weiXinService;
	
	public AttendDevicePojo saveVisitorInfo(Map<String, String> map) {
		// TODO Auto-generated method stub
		String userName = map.get("userName");
		String idCard = map.get("idCard");
		String phone = map.get("phone");
		String personImg = map.get("personImg");
		String personImgBaseEncode = map.get("personImgBaseEncode");
		
		String deviceId = map.get("deviceId");
		//获取考勤机信息 
		AttendDevicePojo devicePojo = visitorMapper.getDeviceInfoById(deviceId);
		if (devicePojo == null) {
			throw new ServiceException("无法查询相应设备,请核对设备ID："+deviceId);
		}
		String company = devicePojo.getCompany();
		String userId = null;
		//通过身份证和公司获取是否在本公司访客中已有记录
		Map<String,String> visitorInfo = visitorMapper.getVisitorInfoByIdCard(idCard,company);
		if(visitorInfo!=null && !"".equals(visitorInfo.get("id"))) {//有了就获取原先访客人员
			userId = visitorInfo.get("id");
			//更新头像信息
			visitorMapper.updateVisitorInfo(userId,personImg,personImgBaseEncode);
		}else {//没有则保存数据
			map.put("company", company);
			//存入数据库
			//设置userId 
			com.ray.util.dk.GUID guid = com.ray.util.dk.GUID.getInstance();
			userId = "FK"+guid.getGuid();
			map.put("id", userId);
			visitorMapper.saveVisitorInfo(map);
		}
		//异步通知卡机
		if(devicePojo.getDeviceType().equals(2)) {
			sendMsgToLowerHairUserToEquipmentForAddVisitor(userId,devicePojo.getDeviceId());
		}
		return devicePojo;
	}
	
	
	public String sendMsgToLowerHairUserToEquipmentForAddVisitor(String userId , String equipment) {
		ConfigUtil.setPropertiesName("db.properties");
		ConfigUtil.init();
		String lowerHairUserToEquipmentUrl=ConfigUtil.getValue("dk.lowerHairUserToEquipment");
		System.out.println("准备开始执行异步任务...");
	    final Object context = "上下文信息";
	 
        new CallBackTask(new CallBackBody() {
            @Override
			public
            void execute(Object context) throws Exception {
                System.out.println("\n正在执行耗时操作...");
                System.out.println(context);
                Thread.sleep(1000);
        		WeixinTemplateSender.httpRequest(lowerHairUserToEquipmentUrl+"/api/v1/record/lowerHairVisitorToEquipment?userId="+userId+"&equipmentNo="+equipment, "GET", null);
                System.out.println("\n执行完成！");
            }
 
            public void onSuccess(Object context) {
                System.out.println("\n成功后的回调函数...");
                System.out.println(context);
            }
 
            public void onFailure(Object context) {
                System.out.println("\n失败后的回调函数...");
                System.out.println(context);
            }
	      }).start(context);
		 System.out.println("\n异步任务已经开始，请等待完成...");
		return null;
	}
	
	
	public void sendClockMessage(Map<String, Object> map) {
		String accessToken=weiXinService.getAccessToken(null); 
		String userCheckTime = map.get("userCheckTime")==null?"":map.get("userCheckTime").toString();
		String guid = map.get("guid")==null?"":map.get("guid").toString();
		String userId = map.get("userId").toString();
		//通过userId去查visitor_info
		Map<String, String> visitorInfo = visitorMapper.getVisitorInfoById(userId);
		String userName = visitorInfo.get("userName");
		map.put("userPhone", visitorInfo.get("phone"));
		map.put("userIdCard", visitorInfo.get("idCard"));
		//拿着guid查询到考勤机的基础体温和本人的体温
    	List<Map<String, Object>> deviceManagerList =  visitorMapper.getDeviceByGuid(guid,visitorInfo.get("company"));
    	//如果超过基础体温则通知考勤机管理人
    	for(Map<String, Object> deviceManager : deviceManagerList) {
    		//打卡人的体温
    		String dkTemperature = deviceManager.get("temperature")!=null?deviceManager.get("temperature").toString():"0";
    		//打卡设备标准体温
    		String temperatureBasic = deviceManager.get("temperatureBasic")!=null?deviceManager.get("temperatureBasic").toString():"0";
    		//管理人的openId
    		String managerOpenId = deviceManager.get("openid")!=null?deviceManager.get("openid").toString():"";
    		
    		//打卡设备的codeName
    		String codeName = deviceManager.get("codeName")!=null?deviceManager.get("codeName").toString():"";
    		//打卡设备的codeId
    		String codeId = deviceManager.get("codeId")!=null?deviceManager.get("codeId").toString():"";
    		//打卡设备的codeArea
    		String codeArea = deviceManager.get("codeArea")!=null?deviceManager.get("codeArea").toString():"";
    		/*如果体温高于标准值 ,并且有管理人员微信  则通知管理人员*/
    		if(!"".equals(managerOpenId) && Double.valueOf(dkTemperature).compareTo(Double.valueOf(temperatureBasic))>0) {
    			String msg = "体温:"+dkTemperature+" 高于阀值 "+temperatureBasic +"请及时处理";
    			com.alibaba.fastjson.JSONObject data = WeixinTemplateList.packJsonToCheckWork("考勤打卡异常提醒", "异常人员 访客("+userName+")", "", userCheckTime,msg , null, null, null, null, "#f00");
    			String message = WeixinTemplateSender.sendWechatmsgToUser(managerOpenId, "X7ZQo8XNaQf_qS63eV1R6oqXeo1GSXBXSU6w0pS9esI", null, data, accessToken);
    			if("success".equals(message)) {
    				message = userName+"消息发送成功";
    			}else {
    				message = userName+"消息发送异常："+message;
    			}
    		}
    		/*有地区码*/
    		if(!"".equals(codeName)) {
    			String userPhone = map.get("userPhone").toString();
    			String userIdCard = map.get("userIdCard").toString();
    			String localCodeMsg = dingTalkService.sendlocalCode(userName,userPhone,userIdCard, codeName, codeId, codeArea);
    			System.out.println(localCodeMsg);
    			JSONObject strRet = JSONObject.parseObject(localCodeMsg);
    			if(strRet.get("success")!=null&&!"1".equals(strRet.get("success").toString()) ) {//不正常
        			com.alibaba.fastjson.JSONObject data = WeixinTemplateList.packJsonToCheckWork("地方码异常:"+codeName, "异常人员 访客("+userName+")", "", userCheckTime,strRet.get("msg").toString() , null, null, null, null, "#f00");
        			String message = WeixinTemplateSender.sendWechatmsgToUser(managerOpenId, "X7ZQo8XNaQf_qS63eV1R6oqXeo1GSXBXSU6w0pS9esI", null, data, accessToken);
        			if("success".equals(message)) {
        				message = userName+"消息发送成功";
        			}else {
        				message = userName+"消息发送异常："+message;
        			}
    			}
    		}
    	}
	}


	public DatatablesViewPageBean<List<Map>> queryAttendance(Map<String, Object> map) {
		int count=0;
		DatatablesViewPageBean<List<Map>> dtcpb=new DatatablesViewPageBean<List<Map>>();
		count=visitorMapper.queryAttendanceCount(map);
		dtcpb.setReturnData(count>0?(ArrayList) visitorMapper.queryAttendance(map): new ArrayList());
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}


	public DatatablesViewPageBean<List<Map>> queryVisitorList(Map<String, Object> map) {
		int count=0;
		DatatablesViewPageBean<List<Map>> dtcpb=new DatatablesViewPageBean<List<Map>>();
		count=visitorMapper.queryVisitorCount(map);
		dtcpb.setReturnData(count>0?(ArrayList) visitorMapper.queryVisitor(map): new ArrayList());
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}


	public void deleteVisitorById(Map<String, Object> map) {
		if (map.get("userId") == null) {
			throw new ServiceException("缺少参数 userId");
		}
		visitorMapper.deleteVisitorById(map);
		//获取这个人在本公司所有关联的设备账号
		List<Map> visitLog = visitorMapper.queryAttendance(map);
		//去重访客中的设备 类型是 2 则发送到 2 第一代
		List<AttendDevicePojo> devicePojosForTwo = new ArrayList<>();
		for(Map ev : visitLog) {
			if("2".equals(ev.get("deviceType").toString())) {
				String deviceNo = ev.get("deviceNo").toString();
				//将卡机中删除  map.get("userId") deviceNo
				AttendDevicePojo pojo = new AttendDevicePojo();
				pojo.setDeviceId(deviceNo);
				pojo.setDeviceType(2);
				devicePojosForTwo.add(pojo);
			}
		}
		if (devicePojosForTwo.size()>0) {
			basicDataService.sendMsgToLowerHairUserToEquipmentForDelete(map.get("userId").toString(), devicePojosForTwo);
		}
		
		
	}
    
	
}